package com.example.loganalysis.services;

import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.core.io.FileSystemResource;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileWriter;

@Service
public class IpfsService {

    @Value("${ipfs.add.url}")
    private String ipfsAddUrl;
    private final RestTemplate restTemplate;

    public IpfsService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public String uploadLogToIpfs(String logContent, String fileName) throws Exception {
        File tempFile = null;
        try {
            // 创建临时文件
            tempFile = new File(System.getProperty("java.io.tmpdir"), fileName);
            try (FileWriter writer = new FileWriter(tempFile)) {
                writer.write(logContent);
            }

            // 创建 multipart 请求
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);

            FileSystemResource resource = new FileSystemResource(tempFile);
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("file", resource);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

            // 发送请求到 IPFS
            ResponseEntity<String> response = restTemplate.exchange(
                    ipfsAddUrl,
                    HttpMethod.POST,
                    requestEntity,
                    String.class
            );

            if (response.getStatusCode().is2xxSuccessful() && response.getBody() != null) {
                return parseIpfsHash(response.getBody());
            } else {
                throw new Exception("Failed to upload log file to IPFS. Response: " + response.getBody());
            }
        } catch (Exception e) {
            throw new Exception("Error uploading log file to IPFS: " + e.getMessage(), e);
        } finally {
            // 删除临时文件
            if (tempFile != null && tempFile.exists()) {
                tempFile.delete();
            }
        }
    }

    private String parseIpfsHash(String responseBody) {
        // 示例解析，假设返回值为 {"Hash": "QmYourCustomHash"}
        return new org.json.JSONObject(responseBody).getString("Hash");
    }

    // 上传文件到 IPFS
    public String uploadFileToIpfs(byte[] fileContent, String fileName) throws Exception {
        // 创建一个 MultiValueMap 用于存储文件和元数据
        MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
        body.add("file", new ByteArrayResource(fileContent) {
            @Override
            public String getFilename() {
                return fileName; // 设置文件名
            }
        });

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.MULTIPART_FORM_DATA);

        // 构建请求实体
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(body, headers);

        // 发送 POST 请求
        ResponseEntity<String> response = restTemplate.exchange(ipfsAddUrl, HttpMethod.POST, requestEntity, String.class);

        if (response.getStatusCode().is2xxSuccessful()) {
            // 假设响应中包含 IPFS 哈希
            return extractIpfsHash(response.getBody());
        } else {
            throw new Exception("Failed to upload file to IPFS. Response: " + response.getStatusCode());
        }
    }


    // 解析 IPFS 上传响应，提取 IPFS 哈希
    private String extractIpfsHash(String responseBody) {
        // 假设响应是 JSON 格式，包含 "Hash" 字段
        try {
            JSONObject json = new JSONObject(responseBody);
            return json.optString("Hash", null);
        } catch (JSONException e) {
            throw new RuntimeException("Failed to parse IPFS response: " + responseBody, e);
        }
    }
}
